package com.maq.persistence;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.maq.domain.vo.BoyBase;
import com.maq.domain.vo.GirlBase;
import com.maq.domain.vo.supper.PeopleBase;

@Repository
public class PeopleBaseDao {
	@Autowired
	private SessionFactory sessionFactory;

	public List<? extends PeopleBase> findAllPeopleBase(int _page, int pageSize, int gender) {
		Session session = sessionFactory.getCurrentSession();
		int beginRow = (_page - 1) * pageSize;
		@SuppressWarnings("rawtypes")
		Class clazz = null;
		if (gender == 1) {
			clazz = BoyBase.class;
		} else if (gender == 0) {
			clazz = GirlBase.class;
		}
		Criteria cri = session.createCriteria(clazz);
		cri.add(Restrictions.ne("status", 3));// 第一次我写成了"3"半天没弄好
		cri.setFirstResult(beginRow); // 从第beginRow条开始
		cri.setMaxResults(pageSize);// 获取pageSize条数据
		if (gender == 1) {
			List<BoyBase> peopleBases = cri.list();
			return peopleBases;
		} else if (gender == 0) {
			List<GirlBase> peopleBases = cri.list();
			return peopleBases;
		}
		return null;
	}

	public PeopleBase findPeopleBase(PeopleBase peopleBase) {
		Session session = sessionFactory.getCurrentSession();

		if (peopleBase instanceof BoyBase) {
			return (BoyBase) session.get(BoyBase.class, ((BoyBase) peopleBase).getId());
		} else {
			return (GirlBase) session.get(GirlBase.class, ((GirlBase) peopleBase).getId());
		}
	}

	public void saveOrUpdate(PeopleBase peopleBase) {
		Session session = sessionFactory.getCurrentSession();
		
		if (peopleBase instanceof BoyBase) {
			session.saveOrUpdate("BoyBase", peopleBase);
		} else {
			session.saveOrUpdate("GirlBase", peopleBase);
		}

	}

	public PeopleBase findPeopleByEmailOrPhone(String tempString) {
		Session session = sessionFactory.getCurrentSession();
		Criteria cri=null;
		List<? extends PeopleBase> peopleBases;
		Class[] baseClass = { BoyBase.class, GirlBase.class };
		for (Class clazz : baseClass) {
			cri = session.createCriteria(clazz);
			if (tempString.contains("@")) {
				cri.add(Restrictions.eq("email", tempString));
			}else{
				cri.add(Restrictions.eq("phone", tempString));
			}
			peopleBases=cri.list();
			if (peopleBases.size()==1) {
				return peopleBases.get(0);
			}
		}
		return null;
	}

}
